<!------------添加标签组件------------>
<template>
    <el-tag v-for="(tag, index) in tagList" :key="index" closable :disable-transitions="false" @close="handleRemove(index, tag)" size="large">
        <div :contenteditable="isEdit" @blur="handleEditTag($event, index)">{{ tag }}</div>
    </el-tag>
    <el-input
        v-if="inputStatus"
        class="inline-block w-36"
        ref="inputRef"
        v-model.trim="tagInput"
        @keyup.enter="handleAddTag(index)"
        @blur="handleAddTag(index)"
        placeholder="输入完成后回车"
    />
    <el-button v-else class="border-dashed" @click="showInput"> + {{ btnText }} </el-button>
</template>
<script setup>
import { ref, nextTick, watch } from 'vue'
const props = defineProps({
    modelValue: {
        type: Array,
        default: () => [],
    },
    isEdit: {
        type: Boolean,
        default: true,
    },
    btnText: {
        type: String,
        default: '添加',
    },
}) // 父组件传递的值
const emits = defineEmits(['update:modelValue','change']) // 传递给父组件的值
let tagList = ref(props.modelValue) // 标签列表
let inputRef = ref(null) // 输入框实例
let tagInput = ref(null) // 输入框的值
let inputStatus = ref(false) // 输入框的状态

watch(
    () => props.modelValue,
    (newVal) => {
        tagList.value = newVal
    },
    { deep: true }
)

watch(
    () => tagList.value,
    (newVal) => {
        emits('update:modelValue', newVal)
    },
    { deep: true }
)

// 修改tag的值
const handleEditTag = (event, index) => {
    if (event.target.innerText) {
        tagList.value[index] = event.target.innerText
    } else {
        tagList.value.splice(index, 1)
    }
    emits('change', tagList.value)
}

// 移除tag
const handleRemove = (index, tag) => {
    tagList.value.splice(tagList.value.indexOf(tag), 1)
    emits('change', tagList.value)
}

// 显示tag输入框
const showInput = () => {
    inputStatus.value = true
    nextTick(() => {
        inputRef.value.focus()
    })
}

// 添加tag
const handleAddTag = () => {
    if (tagInput.value) {
        tagList.value.push(tagInput.value)
    }
    inputStatus.value = false
    tagInput.value = null
    emits('change', tagList.value)
}
</script>
